const AreaExtensionSchema = require('../entity/area/areaextension');
const { generateRandomUUID } = require('../module/tool/common');
const serviceError = require('../module/error/svcerror');
const Order = require('../entity/product/order');
const OrderStatus = require('../module/const/OrderStatus');

// 添加banner图
async function addBanner (areaId, image, path) {
    const AreaExtensionEntity = new AreaExtensionSchema();
    try {
        const id = generateRandomUUID();
        await AreaExtensionEntity.getModel().findOneAndUpdate({ areaId: areaId }, {
            $push: {
                banner: {
                    id,
                    image,
                    path
                }
            }
        });
        return id;
    } catch (e) {
        throw new serviceError.CommonServiceError('轮播图插入失败');
    }
}

// 更新banner
async function updateBanner (areaId, image, link, id) {
    const AreaExtensionEntity = new AreaExtensionSchema();
    try {
        await AreaExtensionEntity.getModel().updateOne(
            { areaId: areaId, 'banner.id': id },
            { $set: { 'banner.$.image': image, 'banner.$.path': link } });
    } catch (e) {
        throw new serviceError.CommonServiceError('轮播图更新失败');
    }
    return 1;
}

// 删除banner
async function deleteBanner (areaId, bannerId) {
    const AreaExtensionEntity = new AreaExtensionSchema();
    await AreaExtensionEntity.getModel().findOneAndUpdate({ areaId: areaId }, { $pull: { banner: { id: bannerId } } });
    return 1;
}

// 添加Activitybanner图
async function addActivityBanner (areaId, image, path) {
    const AreaExtensionEntity = new AreaExtensionSchema();
    try {
        const id = generateRandomUUID();
        await AreaExtensionEntity.getModel().findOneAndUpdate({ areaId: areaId }, {
            $push: {
                activityBanner: {
                    id,
                    image,
                    path
                }
            }
        });
        return id;
    } catch (e) {
        throw new serviceError.CommonServiceError('轮播图插入失败');
    }
}

// 更新Activitybanner
async function updateActivityBanner (areaId, image, link, id) {
    const AreaExtensionEntity = new AreaExtensionSchema();
    try {
        await AreaExtensionEntity.getModel().updateOne(
            {
                areaId: areaId,
                'activityBanner.id': id
            },
            {
                $set: {
                    'activityBanner.$.image': image,
                    'activityBanner.$.path': link
                }
            });
    } catch (e) {
        throw new serviceError.CommonServiceError('轮播图更新失败');
    }
    return 1;
}

// 删除Activitybanner
async function deleteActivityBanner (areaId, bannerId) {
    const AreaExtensionEntity = new AreaExtensionSchema();
    await AreaExtensionEntity.getModel().findOneAndUpdate({ areaId: areaId }, { $pull: { activityBanner: { id: bannerId } } });
    return 1;
}

// 订单总览和订单数据
async function orderOverview (areaId, offset, rows, data) {
    offset = parseInt(offset);
    rows = parseInt(rows);
    const orderStatus = Number(data.orderStatus);

    const startTime = data.startTime / 1000;
    const endTime = data.endTime / 1000;

    const OrderModel = new Order().getModel();

    // 支付成功 订单和数量
    const paySuccessQuery = {
        areaId,
        status: { $in: [OrderStatus.Payed.value, OrderStatus.Delivering.value, OrderStatus.Finished.value] },
        createTime: {
            $gt: startTime,
            $lt: endTime
        }
    };
    const paySuccessCount = await OrderModel.countDocuments(paySuccessQuery);
    const payData = await OrderModel.aggregate([
        {
            $match: {
                areaId: Order.toObjectId(areaId),
                status: { $in: [OrderStatus.Payed.value, OrderStatus.Delivering.value, OrderStatus.Finished.value] },
                createTime: {
                    $gte: startTime,
                    $lte: endTime
                }
            }
        },
        {
            $group: {
                _id: null,
                total: { $sum: '$price' }
            }
        }
    ]);
    const payPrice = payData.length > 0 ? payData[0].total : 0;

    // 完成订单和数量
    const finishQuery = {
        areaId,
        status: { $eq: OrderStatus.Finished.value },
        finishTime: {
            $gt: startTime,
            $lt: endTime
        }
    };
    const finishCount = await OrderModel.countDocuments(finishQuery);
    const finishData = await OrderModel.aggregate([
        {
            $match: {
                areaId: Order.toObjectId(areaId),
                status: { $eq: OrderStatus.Finished.value },
                finishTime: {
                    $gte: startTime,
                    $lte: endTime
                }
            }
        },
        {
            $group: {
                _id: null,
                total: { $sum: '$price' }
            }
        }
    ]);
    const finishPrice = finishData.length > 0 ? finishData[0].total : 0;

    // 订单数据
    const findQuery = orderStatus === OrderStatus.Finished.value ? finishQuery : paySuccessQuery;
    // 排序时间
    let sortTime = orderStatus === OrderStatus.Finished.value ? { finishTime: -1 } : { createTime: -1 };

    const orderData = await OrderModel.find(findQuery).sort(sortTime).skip(offset).limit(rows);
    const orderCount = orderStatus === OrderStatus.Finished.value ? finishCount : paySuccessCount;

    return {
        paySuccessCount,
        payPrice,
        finishCount,
        finishPrice,
        orderData,
        orderCount
    };
}

// 查询导出订单数据
async function exportOrder (areaId, data) {
    const orderStatus = Number(data.status);
    const startTime = data.startTime / 1000;
    const endTime = data.endTime / 1000;
    const OrderModel = new Order().getModel();

    let status = orderStatus === 4 ? { $eq: 4 } : { $in: [2, 3, 4] };

    let orderData = [];
    if (orderStatus === 4) {
        orderData = await OrderModel.find({
            areaId,
            status,
            finishTime: {
                $gt: startTime,
                $lt: endTime
            }
        });
    } else {
        orderData = await OrderModel.find({
            areaId,
            status,
            createTime: {
                $gt: startTime,
                $lt: endTime
            }
        });
    }
    return orderData;
}

module.exports = {
    addBanner,
    deleteBanner,
    updateBanner,
    addActivityBanner,
    deleteActivityBanner,
    updateActivityBanner,
    orderOverview,
    exportOrder
};
